package com.monolithiot.sso.controller.restservice;

import com.monolithiot.sso.common.entity.DeviceAuthorization;
import com.monolithiot.sso.common.entity.User;
import com.monolithiot.sso.common.exception.TargetNotFondException;
import com.monolithiot.sso.service.DeviceAuthorizationService;
import com.monolithiot.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 2019/2/16 Create by 郭文梁
 * DeviceAuthorizationRestService
 * 设备授权服务，仅供服务间内部调用
 *
 * @author 郭文梁
 * @date 2019/2/16
 */
@RestController
@RequestMapping("/service/da")
public class DeviceAuthorizationRestController {
    private final DeviceAuthorizationService deviceAuthorizationService;
    private final UserService userService;

    @Autowired
    public DeviceAuthorizationRestController(DeviceAuthorizationService deviceAuthorizationService, UserService userService) {
        this.deviceAuthorizationService = deviceAuthorizationService;
        this.userService = userService;
    }

    /**
     * 根据用户ID查找设备授权
     *
     * @param userId 用户ID
     * @return DeviceAuthorization Entity list
     * @throws TargetNotFondException 用户不存在时抛出
     */
    @GetMapping("/by-user")
    public List<DeviceAuthorization> listByUser(@RequestParam("userId") Integer userId) throws TargetNotFondException {
        User user = userService.get(userId);
        if (user == null) {
            throw new TargetNotFondException("User for id [" + userId + "] not found");
        }
        return deviceAuthorizationService.findByUserFetchAll(user);
    }
}
